package com.droid.mvvmlib.base;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

/**
 * ViewModel基类
 *
 * @author zyc0617
 * @since 2019/8/18 15:35
 */
public class SuperBaseViewModel<M extends BaseModel, D> extends UiChangeViewModel<M, D> implements SuperBaseModel.IModelListener<D> {

    public final MutableLiveData<D> liveData = new MutableLiveData<>();

    public SuperBaseViewModel(@NonNull Application application) {
        this(application, null);
    }

    public SuperBaseViewModel(@NonNull Application application, M model) {
        super(application, model);
        if (model != null) {
            model.register(this);
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (model != null) {
            model.unRegister(this);
        }
    }

    @Override
    public void tryToRefresh() {
        if (model != null) {
            model.refresh();
        }
    }

    @Override
    public void onSuccess(SuperBaseModel model, D data, String... tag) {
        if (model == this.model) {
            liveData.setValue(data);
            viewStatus.setValue(ViewStatus.SHOW_CONTENT);
        }
    }

    @Override
    public void onFail(SuperBaseModel model, String error, String... tag) {
        errorMessage.setValue(error);
        viewStatus.setValue(ViewStatus.REFRESH_ERROR);
    }
}
